package cn.com.lms.business.learning.web;


import cn.com.lms.business.core.constant.BNZConstants;
import cn.com.lms.business.core.util.ExportUtils;
import cn.com.lms.business.core.util.ServletUtils;
import cn.com.lms.business.core.util.SystemUserUtil;
import cn.com.lms.business.course.service.FbCourseInfoService;
import cn.com.lms.business.learning.persistence.entity.vo.*;
import cn.com.lms.business.learning.service.UserLearningPlanService;
import cn.com.lms.business.user.persistence.entity.SysUserVo;
import com.bnzj.cloud.business.core.persistence.entity.SysDepartment;
import com.bnzj.cloud.business.core.persistence.entity.SysUser;
import com.bnzj.cloud.business.core.service.SysDepartmentService;
import com.bnzj.cloud.business.core.service.SysUserService;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;

import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.util.FbConstant;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Optional;

/*
 * @author liuwei
 * @date 2020/3/18 17:05
 * @desc 员工学习计划统计列表
 */
@Tag(name = "员工学习计划统计列表", description = "员工学习计划统计列表")
@RestController
@RequestMapping("/learning/userPlan")
public class UserLearningPlanController {
    private final static Logger logger = LoggerFactory.getLogger(UserLearningPlanController.class);

    @Autowired
    private UserLearningPlanService userLearningPlanService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private FbCourseInfoService courseInfoService;

    @Autowired
    private SysDepartmentService sysDepartmentService;


    @Operation(summary = "员工学习统计-列表", parameters = {
            @Parameter(name = "limit", description = "分页大小", allowReserved = true, schema = @Schema(type = "int", description = "分页大小"))
            , @Parameter(name = "offset", description = "页码", allowReserved = true, schema = @Schema(type = "int", description = "页码"))
            , @Parameter(name = "userName", required = true, description = "员工名称", schema = @Schema(type = "String"))
            , @Parameter(name = "isRecord", required = true, description = "是否备案", schema = @Schema(type = "String"))
            , @Parameter(name = "deptId", required = true, description = "部门ID", schema = @Schema(type = "Long"))
            , @Parameter(name = "startDate", required = true, description = "开始时间", schema = @Schema(type = "Date"))
            , @Parameter(name = "endDate", required = true, description = "结束时间", schema = @Schema(type = "Date"))})
    @GetMapping("/queryUserStatistics")
    public ResponseResult<Page<UserStatisticsListVo>> queryUserStatistics(HttpServletRequest request) {
        return ResponseResult.success(userLearningPlanService.queryUserStatistics(request));
    }

    @Operation(summary = "员工学习统计列表-查看-学习计划列表", parameters = {
            @Parameter(name = "limit", description = "分页大小", allowReserved = true, schema = @Schema(type = "int", description = "分页大小"))
            , @Parameter(name = "offset", description = "页码", allowReserved = true, schema = @Schema(type = "int", description = "页码"))
            , @Parameter(name = "type", required = true, description = "不传查全部-0未完成-1已完成", schema = @Schema(type = "Integer"))
            , @Parameter(name = "queryName", required = true, description = "计划名称", schema = @Schema(type = "String"))
            , @Parameter(name = "startDate", required = true, description = "开始时间", schema = @Schema(type = "Date"))
            , @Parameter(name = "endDate", required = true, description = "结束时间", schema = @Schema(type = "Date"))})
    @GetMapping("/getUserLearStatisticsView/{userId}")
    public ResponseResult<UserLearningListCount> getUserLearStatisticsView(HttpServletRequest request, @Parameter(in = ParameterIn.PATH, name = "userId", description = "用户id", required = true) @PathVariable Long userId) {
        return ResponseResult.success(userLearningPlanService.getUserLearStatisticsView(request, userId));
    }

    @Operation(summary = "员工学习统计列表-查看-考试列表", parameters = {
            @Parameter(name = "limit", description = "分页大小", allowReserved = true, schema = @Schema(type = "int", description = "分页大小"))
            , @Parameter(name = "offset", description = "页码", allowReserved = true, schema = @Schema(type = "int", description = "页码"))
            , @Parameter(name = "type", required = true, description = "不传查全部-0未完成-1通过 2未通过", schema = @Schema(type = "Integer"))
            , @Parameter(name = "queryName", required = true, description = "考试名称", schema = @Schema(type = "String"))
            , @Parameter(name = "startDate", required = true, description = "开始时间", schema = @Schema(type = "Date"))
            , @Parameter(name = "endDate", required = true, description = "结束时间", schema = @Schema(type = "Date"))})
    @GetMapping("/getUserExamList/{userId}")
    public ResponseResult<UserLearningListCount> getUserExamList(HttpServletRequest request, @Parameter(in = ParameterIn.PATH, name = "userId", description = "用户id", required = true) @PathVariable Long userId) {
        return ResponseResult.success(userLearningPlanService.getUserExamList(request, userId));
    }

    @Operation(summary = "员工学习统计列表-查看-课程列表", parameters = {
            @Parameter(name = "limit", description = "分页大小", allowReserved = true, schema = @Schema(type = "int", description = "分页大小"))
            , @Parameter(name = "offset", description = "页码", allowReserved = true, schema = @Schema(type = "int", description = "页码"))
            , @Parameter(name = "type", required = true, description = "类型id", schema = @Schema(type = "Long"))
            , @Parameter(name = "queryName", required = true, description = "课程名称", schema = @Schema(type = "String"))
            , @Parameter(name = "startDate", required = true, description = "开始时间", schema = @Schema(type = "Date"))
            , @Parameter(name = "endDate", required = true, description = "结束时间", schema = @Schema(type = "Date"))})
    @GetMapping("/getUserCourseList/{userId}")
    public ResponseResult<Page<UserLearningCourseListVo>> getUserCourseList(HttpServletRequest request, @Parameter(in = ParameterIn.PATH, name = "userId", description = "用户id", required = true) @PathVariable Long userId) {
        return ResponseResult.success(userLearningPlanService.getUserCourseList(request, userId));
    }


    @Operation(summary = "员工学习统计列表-查看-详情", parameters = {
            @Parameter(name = "planId", required = true, description = "计划id", schema = @Schema(type = "Long"))})
    @GetMapping("/getUserLearningStageView/{planId}/{userId}")
    public ResponseResult<List<UserLearningStageViewVo>> getUserLearningStageView(@PathVariable(name = "planId", value = "planId") Long planId, @Parameter(in = ParameterIn.PATH, name = "userId", description = "用户id", required = true) @PathVariable Long userId) {
        return ResponseResult.success(userLearningPlanService.getUserLearningStageView(planId, userId));
    }


    @Operation(summary = "员工学习计划统计列表导出", parameters = {
            @Parameter(name = "limit", description = "分页大小", allowReserved = true, schema = @Schema(type = "int", description = "分页大小"))
            , @Parameter(name = "offset", description = "页码", allowReserved = true, schema = @Schema(type = "int", description = "页码"))
            , @Parameter(name = "userName", description = "员工名称", schema = @Schema(type = "String"))
            , @Parameter(name = "isRecord", description = "是否备案", schema = @Schema(type = "String"))
            , @Parameter(name = "deptId", description = "部门ID", schema = @Schema(type = "Long"))
            , @Parameter(name = "startDate", description = "开始时间", schema = @Schema(type = "Date"))
            , @Parameter(name = "endDate", description = "结束时间", schema = @Schema(type = "Date"))
            , @Parameter(name = "isReadOnly", required = true, description = "是否导出只读 true 是 false 否", schema = @Schema(type = "boolean"))})
    @PostMapping("/exportStatistics")
    public void exportStatistics(HttpServletRequest request, HttpServletResponse response) throws IOException {
        OutputStream output = null;
        try {
            output = response.getOutputStream();
            //用户名称
            String userName = request.getParameter("userName");
            //部门ID
            String deptId = request.getParameter("deptId");
            //是否备案
            String isRecord = request.getParameter("isRecord");
            //起始日期
            String startDate = request.getParameter("startDate");
            //结束日期
            String endDate = request.getParameter("endDate");
            //是否导出只读
            Boolean isReadOnly = request.getParameter("isReadOnly") == null ? false : Boolean.valueOf(request.getParameter("isReadOnly"));
            String password = "";
            if (isReadOnly) {
                //如果是导出只读的，需从数据字典读取配置好的密码
                password = courseInfoService.getSysSettingValue(BNZConstants.EXCEL_PASSWORD);
            }
            SysUserVo sysUser = SystemUserUtil.getCurrentUser();
            if (!FbConstant.ADMIN.equals(sysUser.getAccount()) && StringUtils.isEmpty(deptId)) {
                deptId = String.valueOf(sysUser.getDeptId());
            }
            Optional<SysDepartment> department = null;
            if (!StringUtils.isEmpty(deptId)) {
                department = sysDepartmentService.findById(Long.valueOf(deptId));
            }
            SysDepartment sysDepartment = department == null ? null : department.get();
            QueryHelpBean queryHelpBean = userLearningPlanService.userStatisticsQuery(sysDepartment == null ? "" : sysDepartment.getFullName(), startDate, endDate);
            queryHelpBean.setPageable(ServletUtils.initPage());
//            IExpression deptIdCondition = CompareExpression.build("a.id", CompareType.equal, deptId);
            IExpression queryTextCondition = CompareExpression.build("a.account", CompareType.equal, userName).or(
                    CompareExpression.build("a.phone", CompareType.equal, userName).or(
                            CompareExpression.build("a.identity", CompareType.equal, userName).or(
                                    CompareExpression.build("a.cname", CompareType.equal, userName).or(
                                            CompareExpression.build("a.jobType", CompareType.equal, userName)))));

//            IExpression startTimeCondition = CompareExpression.build("a.releaseTime", CompareType.between, "releaseTime", startDate, endDate);
            IExpression isRecodeCondition = CompareExpression.build("a.isRecord", CompareType.equal, isRecord);
            queryHelpBean.addWhere(queryTextCondition, isRecodeCondition);

            List<?> list = userLearningPlanService.exportAll(queryHelpBean);
            Workbook wb = new XSSFWorkbook();//创建XSSFWorkbook对象
            String title = "员工学习计划统计列表";
            ExportUtils.exportExcel(wb, title, list, UserLearningPlanService.getColumnList(), password);
            //输出Excel文件

            String codedFileName = java.net.URLEncoder.encode("员工学习计划统计列表", "UTF-8");
            //设置响应头，
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + codedFileName + ".xls");
            wb.write(output);
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            output.flush();
            output.close();
        }
    }


    /*
     * @author liuwei
     * @date 2020/4/9 18:35
     * @desc //导出学员学习明细报表
     */
    @Operation(summary = "导出学员学习明细报表", parameters = {
            @Parameter(name = "limit", description = "分页大小", allowReserved = true, schema = @Schema(type = "int", description = "分页大小"))
            , @Parameter(name = "offset", description = "页码", allowReserved = true, schema = @Schema(type = "int", description = "页码"))
            , @Parameter(name = "isReadOnly", required = true, description = "是否只读", schema = @Schema(type = "boolean"))
            , @Parameter(name = "startDate", required = true, description = "开始时间", schema = @Schema(type = "Date"))
            , @Parameter(name = "endDate", required = true, description = "结束时间", schema = @Schema(type = "Date"))})
    @PostMapping("/exportDetail/{userId}")
    public void exportDetail(@RequestBody ExportStatisticsVo statisticsVo, HttpServletResponse response, @PathVariable Long userId) throws IOException {
        OutputStream output = null;
        Boolean isReadOnly = statisticsVo.getIsReadOnly();
        Optional<SysUser> sysUser = sysUserService.findById(userId);
        if (!sysUser.isPresent()) {
            return;
        }
        SysUser user = sysUser.get();
        String password = "";
        if (isReadOnly) {
            //如果是导出只读的，需从数据字典读取配置好的密码
            password = courseInfoService.getSysSettingValue(BNZConstants.EXCEL_PASSWORD);
        }

        try {
            output = response.getOutputStream();
            //起始日期
            String startDate = statisticsVo.getStartDate();
            //结束日期
            String endDate = statisticsVo.getEndDate();
            String fileName = "" + user.getCname() + "的学习明细(" + startDate + "~" + endDate + ")";
            QueryHelpBean planHelpBean = userLearningPlanService.userStatisticsViewQuery(userId, null, startDate, endDate);
            QueryHelpBean examHelpBean = userLearningPlanService.QueryUserExamQuery(userId, null, startDate, endDate);
            QueryHelpBean courseHelpBean = userLearningPlanService.QueryUserCourseQuery(userId, startDate, endDate);


            //查看用户学习计划

            planHelpBean.setPageable(ServletUtils.initPage());
            List<?> planList = userLearningPlanService.exportAll(planHelpBean);
            //查看用户考试列表
            examHelpBean.setPageable(ServletUtils.initPage());
            List<?> examList = userLearningPlanService.exportAll(examHelpBean);
            //查看用户课程列表
            courseHelpBean.setPageable(ServletUtils.initPage());
            List<?> courseList = userLearningPlanService.exportAll(courseHelpBean);
            Workbook wb = new XSSFWorkbook();//创建XSSFWorkbook对象
            //导出三个单元格数据
            String courseTitle = "学习计划";
            ExportUtils.exportExcel(wb, courseTitle, planList, UserLearningPlanService.getPlanColumnList(), password);
            String planTitle = "考试";
            ExportUtils.exportExcel(wb, planTitle, examList, UserLearningPlanService.getExamColumnList(), password);
            String examTitle = "课程学习";
            ExportUtils.exportExcel(wb, examTitle, courseList, UserLearningPlanService.getCourseColumnList(), password);
            //输出Excel文件

            String codedFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            //设置响应头，
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + codedFileName + ".xls");

            wb.write(output);
            //导出文件加密
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            output.flush();
            output.close();
        }
    }

}
